package controller

import (
	"fmt"
	"go-data-spider/server/model"
	"net/http"
	"strings"

	"github.com/labstack/echo/v4"
)

// 定义返回结构体，只包含需要的字段
type IndexDataResponse struct {
	Date       string  `json:"date"`       // 保持date字段
	ClosePoint float64 `json:"closePoint"` // 保持closePoint字段
}

// ListIndexDataByCode 根据代码获取指数数据
func ListIndexDataByCode(c echo.Context) error {
	code := strings.TrimSpace(c.Param("code"))
	if code == "" {
		return fmt.Errorf("指数代码不能为空")
	}

	indexDataList, err := model.ListIndexDataByCode(code)
	if err != nil {
		return fmt.Errorf("获取指数数据失败: %v", err)
	}

	// 转换为只包含需要字段的响应结构
	responseData := make([]IndexDataResponse, len(indexDataList))
	for i, data := range indexDataList {
		responseData[i] = IndexDataResponse{
			Date:       data.Date,
			ClosePoint: data.ClosePoint,
		}
	}

	return c.JSON(http.StatusOK, responseData)
}
